package com.zretc.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.zretc.news.commons.AjaxResponse;
import com.zretc.news.entity.Users;
import com.zretc.news.service.UsersService;
import com.zretc.news.service.impl.UsersServiceImpl;

/**
 * Servlet implementation class UsersServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	// UsersServlet要调用service所以这里需要创建
	// UsersService对象
	UsersService us = new UsersServiceImpl();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1设置请求参数
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		Gson gson = new Gson();

		// System.out.println("doGet:... "+request.getReader().readLine());
		System.out.println("doGet:... " + request.getParameter("username"));

		AjaxResponse ajaxResponse = new AjaxResponse("success", 200);

		// 2 获取op的值
		String op = "";
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}

		if ("login".equals(op)) {
			// 获取前台传递过来的查询的关键字
			String username = request.getParameter("username");
			String userpwd = request.getParameter("userpwd");
			Users u = us.login(username, userpwd);
			if (u != null) {
				request.getSession().setAttribute("user", u);
			}
			ajaxResponse.setObj(u);
			System.out.println("ajax :" + ajaxResponse);
			out.print(gson.toJson(ajaxResponse));

		} else if ("yzm".equals(op)) {

		}

		out.close();

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
